package cn.itcast.bos.service.base.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;
import javax.xml.crypto.Data;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.poi.hssf.model.WorkbookRecordList;
import org.apache.xmlbeans.impl.jam.mutable.MSourcePosition;
import org.aspectj.apache.bcel.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.base.OrderRepository;
import cn.itcast.bos.dao.base.WorkBillRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.base.OrderService;
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
	@Autowired
	private FixedAreaRepository fixedAreaRepository;
	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private AreaRepository areaRepository;
	@Autowired
	private WorkBillRepository workBillRepository;
	@Autowired
	private JmsTemplate jmsTemplate;
	
	@Override
	public void saveOrder(Order order) {
		String fixedAreaId=WebClient.create(Constants.CRM_MANAGEMENT_URL
				+"/services/customerService/customer/findFixedAreaIdByAddress"
				+order.getSendAddress()).accept(MediaType.APPLICATION_JSON).get(String.class);
		if (fixedAreaId!=null) {
			FixedArea fixedArea=fixedAreaRepository.findOne(fixedAreaId);
			Iterator<Courier> iterator=fixedArea.getCouriers().iterator();
			if (iterator.hasNext()) {
				Courier courier=iterator.next();
				if (courier!=null) {
					saveOrder(order, courier);
					generateWorkBill(order);
					return;
				}
			}
			
			
		}else {
			Area area=order.getSendArea();
			Area persistArea=areaRepository.findByProvinceAndCityAndDistrict(area.getProvince(),area.getCity(),area.getDistrict());
			for(SubArea subArea:persistArea.getSubareas()){
				if (order.getSendAddress().contains(subArea.getKeyWords())) {
					Courier courier =subArea.getFixedArea().getCouriers().iterator().next();
					if (courier!=null) {
						saveOrder(order, courier);
						generateWorkBill(order);
						return;
					}
				}
				
				
			}
			for (SubArea subArea:persistArea.getSubareas()) {
				if (order.getSendAddress().contains(subArea.getAssistKeyWords())) {
					Courier courier=subArea.getFixedArea().getCouriers().iterator().next();
					if (courier!=null) {
						saveOrder(order, courier);
						generateWorkBill(order);
						return;
					}
				}
			}
			
			
		}
		
	
//		自动分单失败,人工分单
		order.setOrderType("2");
		orderRepository.save(order);
		
		

	}

	private void generateWorkBill(final Order order) {
//		生成工单,发送短信
		WorkBill workBill=new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("新单");
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getRemark());
		final String smsNumber=RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNumber);
		workBill.setOrder(order);
		workBill.setCourier(order.getCourier());
		workBillRepository.save(workBill);
		
		
		jmsTemplate.send("bos_sms", new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage=session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier().getTelephone());
				mapMessage.setString("msg", "短信序号"+smsNumber+",取件地址:"+order.getSendAddress()+",联系人:"+order.getSendName()+",手机:"+order.getSendMobile()+",快递员捎话:"+order.getSendMobileMsg());
				
				return mapMessage;
			}
		});
		workBill.setPickstate("已通知");
		
	}

	private void saveOrder(Order order, Courier courier) {
		System.out.println("自动分单成功");
		order.setCourier(courier);
		order.setOrderTime(new Date());
		order.setOrderNum(UUID.randomUUID().toString());
		order.setOrderType("1");
		order.setStatus("1");
		orderRepository.save(order);
	}

}
